<template>
  <a-tree-select
      v-model="treeCtr.selected"
      :field-names="fieldNames"
      allow-clear allow-search
      :tree-checkable="treeCtr.checkAble"
      :placeholder="treeCtr.tips"
      :disabled="disabled"
      :data="treeCtr.treeData"
      :tree-props="treeCtr.treeProps"
      :tree-checked-strategy="treeCtr.treeCheckedStrategy"
      @change="onChange"
  />
</template>

<script lang="ts" setup name="smart-tree-selector">
import {reactive, watch} from 'vue'
import {RequestUtil, TreeUtil} from '@/utils'

const props = defineProps({
  moduleValue: {
    type: [String, Number, Object, Boolean, Array],
    require: true,
  },

  placeholder: {
    type: String,
    require: false,
    default: '请选择',
  },

  url: {
    type: String,
    require: false,
    default: null,
  },

  topLabel: {
    type: String,
    require: false,
    default: null,
  },
  disabled: {
    type: Boolean,
    required: false,
  },

  multiple: {
    type: Boolean,
    required: false,
    default: false,
  },

    treeCheckedStrategy:{
      type:String,
        required:false,
        default:'all',
    },
})


const fieldNames = {key: 'value', title: 'label', children: 'children'}

const emit = defineEmits(['update:moduleValue'])

const treeCtr = reactive({
  selected: props.moduleValue,
  disabled: props.disabled,
  tips: props.placeholder,
  checkAble: props.multiple,
    treeCheckedStrategy:props.treeCheckedStrategy,
  treeProps: {
    showLine: true,
    checkAble: props.multiple,
    defaultExpandAll: true,
    virtualListProps: {
      height: 400
    }
  },
  treeData: [],
})

const loadDict = async () => {
  const {data} = await RequestUtil.getAjax(props.url)
  if (props.topLabel) {
    treeCtr.treeData = [{label: props.topLabel, value: '0', disabled: false, children: TreeUtil.listToTreeNode(data)}]
  } else {
    treeCtr.treeData = TreeUtil.listToTreeNode(data)
  }
}
if (props.url) loadDict()

const onChange = e => emit('update:moduleValue', e)

watch(() => props.url, () => {
  loadDict()
  treeCtr.selected = '0'
  emit('update:moduleValue', '0')
})
watch(
    () => props.moduleValue,
    (x, y) => {
      if (x !== y) treeCtr.selected = x
    }
)
</script>
